import KPlayer from '@kernel/util/player'
import KUi from '@kernel/util/ui'
import UI from '@data/ui'
import KTable from '@kernel/util/table'
import KUnitType from '@kernel/util/unit_type'
import EventUtil from '@kernel/util/event_util'
import KUnit from '@kernel/util/unit'
import Cache from '@kernel/util/cache'
import ReviveController from '../hero/ReviveController'

const cache = new Cache()
const table = new KTable('英雄池')

// 英雄选择
export default class HeroSelectController {
  private typeIds: number[] = []
  private count = 3
  private mainUI: KUi;
  private refreshUI: KUi;

  constructor(private player: KPlayer) {
    this.mainUI = KUi.searchPath(player, UI.HeroSelect)
    this.refreshUI = KUi.searchPath(player, UI.HeroSelectRefreshBtn)
    this.open()
    this.count++
    this.refresh()
    EventUtil.register('TRIGGER_COMPONENT_EVENT', (data) => {
      if (data.__role_id != this.player.id) {
        return
      }
      // 刷新英雄
      if (data.__ui_event_name == 'RefreshHero') {
        this.refresh()
        return
      }
      // 确认选择英雄
      if (data.__ui_event_name == 'SelectHero') {
        this.confirmSelect(new KUi(<string>data.__comp_name, this.player))
        return
      }
    })
  }

  /**
   * 根据玩家获取实例
   * @param player
   */
  static fromPlayer(player: KPlayer) {
    return cache.get('heroSelect', () => {
      return new HeroSelectController(player)
    })
  }

  /**
   * 打开窗口
   */
  open() {
    this.mainUI.visible(true)
  }

  /**
   * 刷新
   */
  refresh() {
    if (this.count <= 0) {
      return
    }
    // 获取英雄池
    let list = table.toList<{ id: number; type: number }>(['id', 'type'])
    const slist = list.random(2)
    slist.forEach((item, idx) => {
      const hui = KUi.searchPath(this.player, UI.HeroSelectBtn[idx])
      hui.setImage(new KUnitType(item.type).icon)
      this.typeIds[idx] = item.type
    })
    this.count--
    this.refreshUI.setText(`刷新(${this.count})`)
    if (this.count <= 0) {
      this.refreshUI.disable(true)
    }
  }

  /**
   * 确认选择英雄
   */
  confirmSelect(ui: KUi) {
    this.mainUI.visible(false)
    const idx = Number(ui.name.substr(-1)) - 1
    const unit = KUnit.create(this.player, this.typeIds[idx], 0, 0)
    this.player.selectUnit(unit)
    this.player.setData('hero', unit)
    new ReviveController(unit)
  }
}
